package com.km.team.phsystem.web.controller;

import com.km.team.phsystem.beans.vo.ImgUploadResultVo;
import com.km.team.phsystem.common.utils.FileUtils;
import com.km.team.phsystem.web.config.EditorConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Author: jiangjun
 * Date: 2019-01-19
 * Time: 14:36
 * Description: 前端editor上传图片
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private EditorConfig editorConfig;

    @PostMapping("img")
    public ImgUploadResultVo uploadEditorImg(@RequestParam("img") List<MultipartFile> imgs) throws Exception {
        ImgUploadResultVo resultVo = new ImgUploadResultVo();
        String[] urlData = new String[5];
        int index = 0;
        for(MultipartFile img : imgs){
            String fileName = img.getOriginalFilename();
            if(StringUtils.isBlank(fileName)) {
                continue;
            }
            String todayDir = FileUtils.genSaveDir();
            String dir = editorConfig.getSaveDir() + File.separator + todayDir;
            File saveDir = new File(dir);
            if(!saveDir.exists()){
                saveDir.mkdirs();
            }
            String finalFileName =  System.currentTimeMillis() + Math.round(Math.random() * 1000)
                    + fileName;
            String finalPath = saveDir + File.separator + finalFileName;
            File newImage = new File( finalPath);
            img.transferTo(newImage);
            urlData[index++] = todayDir + finalFileName;
        }
        resultVo.setErrno(0);
        resultVo.setData(urlData);
        //返回Ｄto
        return resultVo;
    }
}
